package Queue;

/**
 * ClassName: Deque
 * Package: Queue
 *
 * @Author 马学兴
 * @Create 2023/12/4 15:48
 * @Version 1.0
 * Description:双端队列
 */
public class Deque<E>   {
    private E[] data;
    private int front,tail;
    private int size;
    public Deque(int capacity){
        data= (E[]) new Object[capacity];//不浪费⼀个空间的循环队列
        front=0;
        tail=0;
        size=0;
    }
    public Deque(){
        this(10);
    }
    public int getCapacity(){
        return data.length;
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size==0;
    }
    public void resize(int newCapacity){
        E[] newData = (E[]) new Object[newCapacity + 1];
        for (int i = 0; i < size; i++) {
            newData[i]=data[(i+front)%data.length];
        }
        data=newData;
        front=0;
        tail=size;
    }
    public void addLast(E e) {
        if (size==getCapacity()){
            resize(getCapacity()*2);
        }
        data[tail]=e;
        tail=(tail+1)%data.length;
        size++;
    }
    public void addFront(E e){
        if (size==getCapacity()){
            resize(getCapacity()*2);
        }
        front=front==0? data.length-1:front-1;
        data[front] = e;
        size++;
    }
    public E removeLast() {
        if (isEmpty()){
            throw new IllegalArgumentException("empty");
        }
        E ret=data[front];
        data[front]=null;
        front=(front+1)% data.length;
        size--;
        if (size==getCapacity()/4&&getCapacity()/2!=0){
            resize(getCapacity()/2);
        }
        return ret;
    }
    public E removeFront() {
        if (isEmpty()){
            throw new IllegalArgumentException("empty");
        }
        E ret=data[front];
        data[front]=null;
        tail = tail == 0 ? data.length-1 : tail-1;
        size--;
        if (size==getCapacity()/4&&getCapacity()/2!=0){
            resize(getCapacity()/2);
        }
        return ret;
    }
}
